<?php
declare (strict_types = 1);

namespace app\admin\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\helper\Str;
use think\Model;
use think\response\Json;

/**
 * @mixin \think\Model
 */
class Menu extends BaseMode
{

    // 获取菜单列表
    public static function getMenuList(){
        $menuList = getMenus();
        $menus = [];
        foreach ($menuList as $key => $vo){
            if($vo['type']!='button' && $vo['type']!='function'){
                $menus[] = $vo;
            }
        }
        return self::buildMenuChild(0, $menus);
    }

    //递归:一个方法，可以自己调用自己
    //递归获取子菜单
    public static function buildMenuChild($pid, $menuList,$childkey = 'child',$idkdy = 'id',$pidkey='pid'){
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v[$pidkey]) {
                $node = $v;
                $child = self::buildMenuChild($v[$idkdy], $menuList,$childkey);
                if (!empty($child)) {
                    $node[$childkey] = $child;
                }
                // todo 后续此处加上用户的权限判断
                $treeList[] = $node;
            }
        }
        return $treeList;
    }


    /**
     * 删除
     * @param $id
     * @return Json
     */
    public static function del($id)
    {
        if(self::destroy($id)) return info(true,"删除成功！");
        return info(true,"删除失败！");

    }


    /**
     * 获取数据列表（带分页）
     * @param $parm
     * @return array
     * @throws DbException
     */
    public static function getList($parm){
        $where = self::initParams($parm);
        $list = self::order('sort','asc')
            ->where($where)
            ->paginate()
            ->each(function ($item, $key){
                if($item['pid']===0) $item['pid'] = -1;
                $item['status'] = $item['status']==1?'启用':'禁用';
                return $item;
            });//根据编号倒序排序，每页显示10行
        return [
            'code'  => 0,  //不用修改
            'msg'   => '', //不用修改
            'count' => $list->total(), //获取数据库表中的数据总数
            'data'  => $list->items() //获取当前页面数据
        ];
    }

    /**
     * 保存添加的数据
     * @param array $data
     * @return Json
     */
    public static function saveAdd(array $data)
    {
        //验证数据的合法性
        try {
            validate(\app\admin\validate\Menu::class)
                ->scene('saveadd')
                ->check($data);
        }
        catch (ValidateException $e){
            return info(false,$e->getError());//返回验证的错误信息
        }
        //保存数据到数据库
        $menu = new Menu();
        if($menu->save($data)){
            return info(true,'添加成功！');
        }
        return info(false,'添加失败！');
    }

    /**
     * 根据编号获取一行数据
     * @param int $id
     * @return array|Json|Menu|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getRow($id)
    {
        try {
            validate(\app\admin\validate\Menu::class)
                ->scene('id')
                ->check(['id'=>$id]);
        }
        catch (ValidateException $e) {
            return info(false, $e->getError());
        }
        $row = self::find($id);
        if($row) return $row;
        return [];
    }

    public static function edit(array $data)
    {
        try {
            validate(\app\admin\validate\Menu::class)
                ->scene('edit')
                ->check($data);
        }
        catch (ValidateException $e) {
            return info(false, $e->getError());
        }

        $row = self::find($data['id']);
        if(!$row) return info(false,'修改失败！');
        $row->pid = $data['pid'];
        $row->title = $data['title'];
        $row->icon = $data['icon'];
        $row->href = $data['href'];
        $row->target = $data['target'];
        $row->sort = $data['sort'];
        $row->status = $data['status'];
        $row->remark = $data['remark'];
        if($row->save()){
            return info(true,'修改成功！');
        }
        return info(false,'修改失败！');
    }

    public static function getMenuTreeList()
    {
        $menuList = self::field('id,pid,title,icon,href,target')
            ->where('status', 1)
            ->order('sort', 'asc')
            ->select()->each(function ($item){
                if($item['pid']==0) $item['pid']=-1;
                $item['name']= $item['title'];
                return $item;
            });
        return self::buildMenuChild(-1, $menuList,'children');
    }

    /**
     * 获取菜单的树结构数据
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getMenuTree()
    {
        $menuList = self::field('id,pid,title')
            ->where('status', 1)
            ->order('sort', 'asc')
            ->select()->each(function ($item){
                $item['spread'] = true;
                return $item;
            });
        $menuList = self::buildMenuChild(0, $menuList,'children');
        return $menuList;
    }
}
